<template>
  <div class="ele-body">
    <el-card shadow="never" body-style="padding:22px 22px 0 22px;">
      <!-- 搜索表单 -->
      <el-form
        ref="searchForm"
        :model="table.where"
        label-width="120px"
        @keyup.enter.native="$refs.table.reload({page:{page:1,limit:10}})"
        @submit.native.prevent
      >
        <el-row>
          <el-col :md="8" :sm="12">
            <el-form-item label="关键字:" prop="name">
              <el-input
                v-model="table.where.key"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :md="8" :sm="12">
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                class="ele-btn-icon"
                @click="$refs.table.reload({page:{page:1,limit:10}})"
              >查询
              </el-button>
              <el-button
                @click="(table.where = {}) && $refs.table.reload()"
              >重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card shadow="never">
      <!-- 表格工具栏 -->
      <div class="ele-table-tool">
        <div class="ele-table-tool-title">任务列表</div>
        <div class="ele-table-tool-right">
          <el-button
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="showEdit = true"
          >添加
          </el-button>
        </div>
      </div>
      <!-- 数据表格 -->
      <ele-data-table ref="table" :config="table" :choose.sync="choose" highlight-current-row>
        <template slot-scope="{}">
          <el-table-column
            prop="name"
            label="任务名称"
            show-overflow-tooltip
            min-width="110"
          />
          <el-table-column
            prop="type"
            label="任务类型"
            show-overflow-tooltip
            min-width="135"
          >
            <template slot-scope="{ row }">{{
              row.type.name || ''
            }}</template>
          </el-table-column>
          <el-table-column
            prop="status"
            label="任务状态"
            show-overflow-tooltip
            min-width="135"
          />
          <el-table-column
            prop="person"
            label="对接人"
            show-overflow-tooltip
            min-width="135"
          >
            <template slot-scope="{ row }">{{
              row.person === "None" ? "暂无" : row.person.name
            }}</template>
          </el-table-column>
          <el-table-column
            prop="manage"
            label="负责人"
            show-overflow-tooltip
            min-width="135"
          >
            <template slot-scope="{ row }">{{
              row.manage === "None" ? "暂无" : row.manage[0].name
            }}</template>
          </el-table-column>
          <el-table-column
            prop="start_time"
            label="计划执行时间"
            show-overflow-tooltip
            min-width="135"
          >
            <template slot-scope="{ row }">{{
              row.start_time | moment
            }}</template>
          </el-table-column>
          <el-table-column
            prop="update_time"
            label="更新时间"
            show-overflow-tooltip
            min-width="135"
          >
            <template slot-scope="{ row }">{{
              row.update_time | moment
            }}</template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            min-width="160"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-link
                v-if="scope.row.status ==='待处理'"
                icon="el-icon-edit"
                type="primary"
                :underline="false"
                @click="edit(scope.row)"
              >配置</el-link>
              <el-link
                v-else-if="scope.row.status !=='已完成' || scope.row.status !=='已结束'"
                icon="el-icon-edit"
                type="primary"
                :underline="false"
                @click="check(scope.row)"
              >变更</el-link>
              <el-popconfirm
                title="您确定删除吗？"
                @confirm="del(scope.row.id)"
              >
                <el-link
                  slot="reference"
                  icon="el-icon-delete"
                  type="primary"
                  :underline="false"
                >删除</el-link>
              </el-popconfirm>

              <el-link
                icon="el-icon-finished"
                type="primary"
                :underline="false"
                @click="jump(scope.row)"
              >详情
              </el-link>
            </template>
          </el-table-column>
        </template>
      </ele-data-table>
    </el-card>
    <!-- 编辑弹窗 -->
    <el-dialog
      :title="editForm.id ? '编辑任务' : '新建任务'"
      :visible.sync="showEdit"
      width="600px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :lock-scroll="false"
      @closed="editForm = {}"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="editRules"
        label-width="82px"
        @submit.native.prevent
      >
        <el-form-item label="任务名称:" prop="name">
          <el-input
            v-model="editForm.name"
            placeholder="请输入任务名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="任务目标:" prop="target">
          <el-input
            v-model="editForm.target"
            placeholder="请输入任务目标"
            clearable
          />
        </el-form-item>
        <el-form-item label="任务类型:" prop="type">
          <el-select
            v-model="editForm.type"
            placeholder="请选择任务类型"
            style="width: 100%"
          >
            <el-option
              v-for="(item, key) in assetType"
              :key="'type' + key"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="editForm.type === '1'" label="开始时间:">
          <el-date-picker
            v-model="editForm.start_time"
            type="datetime"
            style="width: 100%"
            placeholder="选择日期时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item v-else-if="editForm.type === '2'" label="起止时间:">
          <el-date-picker
            v-model="timeRange"
            type="datetimerange"
            range-separator="至"
            style="width: 100%"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item v-else-if="editForm.type === '3'" label="执行周期:" prop="cycle_hours">
          <el-input
            v-model="editForm.cycle_hours"
            controls-position="right"
            style="width: 100%"
            type="number"
          >
            <template slot="append">小时</template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="editForm.type === '1' || editForm.type === '3'" label="预定义:" prop="predefine">
          <el-select
            v-model="editForm.predefine"
            placeholder="请选择预定义类型"
            style="width: 100%"
          >
            <el-option
              v-for="(item, key) in perDefineOption"
              :key="'type' + key"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人:" prop="manage">
          <el-select
            v-model="editForm.manage"
            placeholder="请选择负责人"
            style="width: 100%"
            filterable
            remote
            multiple
            reserve-keyword
            :remote-method="romoteManager"
            :loading="managerLoading"
          >
            <el-option
              v-for="item in userOption"
              :key="'manager' + item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="对接人:" prop="person">
          <el-select
            v-model="editForm.person"
            placeholder="请选择对接人"
            style="width: 100%"
            filterable
            remote
            reserve-keyword
            :remote-method="romoteManager"
            :loading="managerLoading"
          >
            <el-option
              v-for="item in userOption"
              :key="'manager' + item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="绑定资产:" prop="asset">
          <el-select
            v-model="editForm.asset"
            placeholder="请选择绑定资产"
            style="width: 100%"
            multiple
            filterable
            remote
            reserve-keyword
            :remote-method="remoteMethod"
            :loading="loading"
          >
            <el-option
              v-for="item in assetOption"
              :key="'asset' + item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务描述:">
          <el-input
            v-model="editForm.description"
            placeholder="请输入任务描述"
            :rows="4"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="showEdit = false">取消</el-button>
        <el-button
          type="primary"
          :loading="editLoading"
          @click="save"
        >保存</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="修改状态"
      width="600px"
      :visible.sync="isShow"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :lock-scroll="false"
      @closed="workflowForm = { status: 'pass'}"
    >
      <el-form
        ref="workflowForm"
        :model="workflowForm"
        label-width="82px"
        @submit.native.prevent
      >
        <el-form-item label="是否确认：" prop="name">
          <el-radio v-model="editForm.status" label="pass">通过</el-radio>
          <el-radio v-model="editForm.status" label="deny">拒绝</el-radio>
        </el-form-item>
        <el-form-item label="操作描述：">
          <el-input
            v-model="editForm.description"
            placeholder="请输入操作描述"
            :rows="4"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="isShow = false">取消</el-button>
        <el-button
          type="primary"
          :loading="editLoading"
          @click="saveWorkflow"
        >保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { taksType, deleteTask } from '@/api/task'
import { getUserList } from '@/api/base'
import taskFormRules from './taskFormRules'
import { assetSelect } from '@/api/asset'
import dayjs from 'dayjs'

export default {
  name: 'TaskList',
  filters: {
    moment: function(value) {
      if (value === 'None') return '暂无'
      return dayjs(value).format('YYYY-MM-DD HH:mm:ss')
    }
  },
  data() {
    return {
      table: {
        url: '/task/task/list/',
        where: {}
      },
      editForm: {
        cycle_hours: 1
      }, // 编辑弹窗数据
      choose: [],
      editRules: taskFormRules,
      showEdit: false, // 是否显示编辑弹窗
      editLoading: false, // 编辑表单加载状态
      assetType: [], // 资产类型
      loading: false,
      managerLoading: false,
      assetOption: [],
      userOption: [],
      timeRange: [],
      perDefineOption: [],
      isShow: false,
      workflowForm: {},
      current: {}
    }
  },
  watch: {
    'editForm.type'(newValue, oldValue) {
      if (newValue === '1' || newValue === '3') {
        this.editRules.predefine = [
          { required: true, message: '请输入预定义', trigger: 'blur' }
        ]
      } else {
        delete this.editRules.predefine
      }
    }
  },
  mounted() {
    this._getAssetType()
    this._getAssetList()
    this._getUserList()
    this._getPerDefine()
  },
  methods: {
    /* 清空选择 */
    clearChoose() {
      this.$refs.table.clearSelection()
    },
    /* 保存编辑 */
    save() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.editLoading = true
          if (typeof this.editForm.id !== 'undefined') {
            // 如果是更新，修改editform的manage,asset
            const manage = []
            this.editForm.manage.forEach(item => {
              manage.push(item.id)
            })
            this.editForm.manage = manage
            const asset = []
            this.editForm.asset.forEach(item => {
              asset.push(item.id)
            })
            this.editForm.asset = asset
          }
          const formData = this.editForm
          formData.manage = formData.manage.toString()
          formData.asset = formData.asset.toString()
          if (this.editForm.type === '1') {
            formData.start_time = dayjs(formData.start_time).format('YYYY-MM-DD HH:mm:ss')
          }
          if (this.editForm.type === '2') {
            formData.start_time = dayjs(this.timeRange[0]).format('YYYY-MM-DD HH:mm:ss')
            formData.end_time = dayjs(this.timeRange[1]).format('YYYY-MM-DD HH:mm:ss')
          }
          const url = this.editForm.id ? `/task/task/update/${this.editForm.id}/` : '/task/task/create/'
          this.$http.post(url, formData).then(res => {
            this.editLoading = false
            if (res.data.code === 0) {
              this.showEdit = false
              this.$message({ type: 'success', message: '保存成功' })
              this.$refs.table.reload()
            } else {
              this.$message({ type: 'error', message: res.data.msg })
            }
          })
        } else {
          return false
        }
      })
    },
    /* 编辑 */
    edit(row) {
      this.$http.get(`/workflow/ticket/details/${row.ticket_id}/`).then(res => {
        // 获得任务详情
        const data = res.data.data.info
        const formData = {
          id: data.id,
          name: data.name,
          type: data.type.id,
          target: data.target,
          cycle_hours: data.cycle_hours,
          person: data.person.id,
          description: data.description
        }
        if (data.type.id === '2') {
          formData.start_time = dayjs(data.start_time).format('YYYY-MM-DD HH:mm:ss')
          formData.end_time = dayjs(data.end_time).format('YYYY-MM-DD HH:mm:ss')
          this.timeRange = [data.start_time, data.end_time]
        }
        this.editForm = Object.assign({}, formData)
      })
      this.showEdit = true
    },
    /* 跳转 */
    jump(row) {
      this.$router.push(`/task/detial/${row.ticket_id}`)
    },
    /* 获得资产类型 */
    _getAssetType() {
      taksType().then(res => {
        this.assetType = res.data.data
      })
    },
    /* 删除资产 */
    del(id) {
      deleteTask(id).then(res => {
        if (res.data.code === 0) {
          this.$message('删除成功')
          this.$refs.table.reload()
        }
      })
    },
    /* 获得资产列表 */
    _getAssetList(key) {
      assetSelect(key).then(res => {
        if (res.data.data !== []) {
          this.assetOption = res.data.data
        }
      })
    },
    /* 获得用户列表 */
    _getUserList(key) {
      getUserList(key).then(res => {
        if (res.data.data.length !== 0) {
          this.userOption = res.data.data
        }
      })
    },
    /* 用户远程搜索 */
    async romoteManager(query) {
      if (query !== '') {
        this.loading = true
        await this._getUserList(query)
        this.loading = false
      } else {
        await this._getUserList()
      }
    },
    /* 资产绑定远程搜索 */
    async remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        await this._getAssetList(query)
        this.loading = false
      } else {
        await this._getAssetList()
      }
    },
    /* 获得预定义列表 */
    _getPerDefine() {
      this.$http.get('/scanner/base/list/predefine/').then(res => {
        this.perDefineOption = res.data.data
      })
    },
    /* 审批任务 */
    check(row) {
      this.isShow = true
      this.current = row
    },
    saveWorkflow() {
      this.editLoading = true
      const url = `/workflow/ticket/action/${this.editForm.status}/${this.current.id}/`
      this.$http.post(url, { description: this.editForm.description }).then(res => {
        this.editLoading = false
        const { data } = res
        if (data.code === 0) {
          this.$message({ message: data.msg, type: 'success' })
          this.$refs.table.reload()
          this.isShow = false
        } else {
          this.$message({ message: data.msg, type: 'error' })
        }
      })
    }
  }
}
</script>

<style scoped>
.el-link {
  margin: 0 2px;
}
</style>
